<template>
  <div class="family-tree-visualization">
    <a-page-header @back="goBack" title="家族树可视化">
    </a-page-header>
    
    <div class="controls">
      <a-select 
        v-model:value="familyTreeStore.selectedFamilyTree" 
        placeholder="选择家族树" 
        @change="loadFamilyTreeData"
        style="width: 300px; margin-right: 20px;"
      >
        <a-select-option
          v-for="tree in familyTreeStore.familyTrees"
          :key="tree.id"
          :value="tree.id"
        >
          {{ tree.name }}
        </a-select-option>
      </a-select>
      
      <a-button type="primary" @click="refresh" :loading="loading">刷新</a-button>
    </div>
    
    <div class="family-tree-container">
      <div v-if="!familyTreeStore.selectedFamilyTree" class="placeholder">
        <a-empty description="请选择一个家族树查看族谱" />
      </div>
      
      <div v-else-if="familyTreeStore.generations.length === 0" class="placeholder">
        <a-empty description="该家族树暂无成员信息" />
      </div>
      
      <div v-else class="family-tree">
        <div class="generation" v-for="(generation, index) in familyTreeStore.generations" :key="index">
          <h3>第{{ index + 1 }}代</h3>
          <div class="members">
            <div 
              v-for="member in generation" 
              :key="member.id"
              class="member-card"
              :class="{ 'highlight': highlightedMember && highlightedMember.id === member.id }"
              @click="highlightMember(member)"
            >
              <div class="member-info">
                <div class="avatar">
                  <a-avatar :icon="member.gender === 'M' ? UserOutlined : UserOutlined" />
                </div>
                <div class="details">
                  <div class="name">{{ member.name }}</div>
                  <div class="relation-info">
                    <span v-if="member.fatherName || member.motherName">
                      父: {{ member.fatherName || '未知' }} 
                      母: {{ member.motherName || '未知' }}
                    </span>
                    <span v-if="member.spouseName">
                      配偶: {{ member.spouseName }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 成员详情对话框 -->
    <a-modal v-model:open="dialogVisible" :title="selectedMember ? selectedMember.name + ' 的详细信息' : ''" width="50%">
      <div v-if="selectedMember" class="member-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="姓名">{{ selectedMember.name }}</a-descriptions-item>
          <a-descriptions-item label="性别">
            <a-tag :color="selectedMember.gender === 'M' ? 'blue' : 'pink'">
              {{ selectedMember.gender === 'M' ? '男' : '女' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="出生日期">
            {{ formatDate(selectedMember.birthDate) }}
          </a-descriptions-item>
          <a-descriptions-item label="去世日期">
            {{ formatDate(selectedMember.deathDate) || '在世' }}
          </a-descriptions-item>
          <a-descriptions-item label="家族树ID">{{ selectedMember.familyTreeId }}</a-descriptions-item>
          <a-descriptions-item label="地理位置">
            {{ selectedMember.latitude }}, {{ selectedMember.longitude }}
          </a-descriptions-item>
        </a-descriptions>
        
        <div class="biography" v-if="selectedMember.biography">
          <h4>简介</h4>
          <p>{{ selectedMember.biography }}</p>
        </div>
      </div>
      
      <template #footer>
        <a-button @click="dialogVisible = false">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, watch, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useFamilyTreeStore } from '../stores/familyTree'
import { UserOutlined } from '@ant-design/icons-vue'

export default {
  name: 'FamilyTreeVisualization',
  components: {
    UserOutlined
  },
  setup() {
    const router = useRouter()
    const familyTreeStore = useFamilyTreeStore()
    const dialogVisible = ref(false)
    const selectedMember = ref(null)
    const highlightedMember = ref(null)
    const loading = ref(false)
    
    // 使用 useRequest 获取家族树列表
    const { loading: fetchLoading, refetch: fetchFamilyTrees } = familyTreeStore.useFetchFamilyTrees()
    
    // 更新加载状态
    watch(fetchLoading, (newVal) => {
      loading.value = newVal.value
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    // 加载家族树数据
    const loadFamilyTreeData = async (familyTreeId) => {
      if (!familyTreeId) return
      
      try {
        loading.value = true
        const result = await familyTreeStore.loadFamilyTreeData(familyTreeId)
        if (!result.success) {
          message.error(result.message || '加载家族树数据失败')
        }
      } catch (error) {
        message.error('加载家族树数据失败')
        console.error('加载家族树数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 高亮成员
    const highlightMember = (member) => {
      highlightedMember.value = member
    }
    
    // 刷新数据
    const refresh = async () => {
      try {
        await fetchFamilyTrees()
        if (familyTreeStore.selectedFamilyTree) {
          await loadFamilyTreeData(familyTreeStore.selectedFamilyTree)
        }
      } catch (error) {
        message.error('刷新数据失败')
        console.error('刷新数据失败:', error)
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    // 组件挂载时获取家族树列表
    onMounted(async () => {
      try {
        await fetchFamilyTrees()
      } catch (error) {
        message.error('获取家族树列表失败')
        console.error('获取家族树列表失败:', error)
      }
    })
    
    // 组件卸载前清理
    onUnmounted(() => {
      // 清理可能的定时器或事件监听器
    })
    
    return {
      familyTreeStore,
      dialogVisible,
      selectedMember,
      highlightedMember,
      loading,
      UserOutlined,
      formatDate,
      loadFamilyTreeData,
      highlightMember,
      refresh,
      goBack
    }
  }
}
</script>

<style scoped>
.family-tree-visualization {
  padding: 20px;
}

.controls {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.family-tree-container {
  margin-top: 20px;
}

.placeholder {
  text-align: center;
  padding: 40px 0;
}

.family-tree {
  overflow-x: auto;
  padding: 20px 0;
}

.generation {
  margin-bottom: 30px;
}

.generation h3 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.members {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.member-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 15px;
  width: 250px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
}

.member-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #1890ff;
}

.member-card.highlight {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.member-info {
  display: flex;
  align-items: center;
}

.avatar {
  margin-right: 15px;
}

.details {
  flex: 1;
}

.name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.relation-info {
  font-size: 12px;
  color: #666;
}

.relation-info span {
  display: block;
  line-height: 1.4;
}

.member-detail h4 {
  margin: 20px 0 10px 0;
}

.biography p {
  line-height: 1.6;
  color: #333;
}
</style>